import Toast from '@vant/weapp/toast/toast';
import {
  showModel,
  showMsg
} from '../../utils/config'
var WXBizDataCrypt = require('../../utils/WXBizDataCrypt') //解密手机号
import {
  reqWxUserInfo,
  reqBindWx,
  reqUnBindWx,
  reqBindMobile,
  reqOrgCount,
  reqGetPhoneNum
} from '../../request/api.js'
const app = getApp()
const exitLoginBehavior = require('../behaviors/personal/exitLogin.js')
Page({
  behaviors: [exitLoginBehavior],
  data: {
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
    srcInfoBg: '../../statics/images/personal-center/info_bg.png',
    srcDefaultAvatar1: '../../statics/images/personal-center/touxiang1.png',
    srcDefaultAvatar2: '../../statics/images/personal-center/touxiang2.png',
    srcDefaultAvatar3: '../../statics/images/personal-center/touxiang3.png',
    srcDefaultAvatar4: '../../statics/images/personal-center/touxiang4.png',
    srcDefaultAvatar5: '../../statics/images/personal-center/touxiang5.png',
    srcDefaultAvatar6: '../../statics/images/personal-center/touxiang6.png',
    srcUsername: '../../statics/images/personal-center/default_avatar.png',
    srcMobile: '../../statics/images/personal-center/mobile_icon.png',
    srcWechat: '../../statics/images/personal-center/wechat_icon.png',
    srcPwd: '../../statics/images/personal-center/pwd_icon.png',
    srcAbout: '../../statics/images/personal-center/about_icon.png',
    srcHelp: '../../statics/images/personal-center/help_icon.png',
    srcRightArrow: '../../statics/images/personal-center/right_arrow_icon.png',
    danwei: '../../statics/images/wode/danwei.png',
    zhongzhi: '../../statics/images/wode/zhongzhi.png',
    subions: '../../statics/images/mood-smile@3x.png',
    weixin: '../../statics/images/wode/weixin.png',
    tuandui: '../../statics/images/wode/tuandui.png',
    shouji: '../../statics/images/wode/shouji.png',
    kefu: '../../statics/images/wode/kefu.png',
    tenantId: '',
    orgName: '', //单位名称
    username: '',
    nickname: '',
    mobile: '',
    avatar: '',
    wxNickName: '',
    wxAvatar: '',
    openId: '',
    // isBindWx: true, //是否可操作绑定/解绑微信
    // isBindMobile: true, //是否可操作绑定/解绑手机
    teamTotal: 0, //团队人数
    isProprietor: true,
    orgId: "",
    innerShow: false,
    orgId2: "",

    showCancelAccount: '', //注销弹窗
  },


  onLoad: function () {
    this.getUserInfo1()
  },
  onShow() {
    console.log(app.globalData.avatar);
    this.setData({
      avatar: app.globalData.avatar || wx.getStorageSync('avatar'),
      isProprietor: app.globalData.isProprietor,
      orgId: app.globalData.orgId,
      orgId2: app.globalData.orgId2,
      tenantId: app.globalData.tenantId,
    })
    this.getTabBar().init(); //tabbar
    this.getUserInfo2()
    // if (!app.globalData.isProprietor) {
    //     // 装维人员
    //     this.getTeamTotal()
    // }
  },

  // 获取个人信息load
  getUserInfo1() {
    this.setData({
      username: app.globalData.username,
      mobile: app.globalData.mobile,
      descriptionRole: app.globalData.descriptionRole,
      orgName: app.globalData.orgName,
      wxNickName: app.globalData.wxNickName,
      wxAvatar: app.globalData.wxAvatar,
    })
  },

  // 获取个人信息show
  getUserInfo2() {
    this.setData({
      orgName: app.globalData.orgName,
      username: app.globalData.username,
      nickname: app.globalData.nickname,
      openId: app.globalData.openId,
    })
  },

  // 去个人信息
  goUserInfo() {
    wx.navigateTo({
      url: '/pages/personal-inside-page/user-info/user-info',
    })
  },

  // 去单位切换
  orgToggleClick() {
    wx.navigateTo({
      url: `/pages/personal-inside-page/org/org?mark=personalCenter`,
    })
  },
  // 团队人总数
  async getTeamTotal() {
    const res = await reqOrgCount(app.globalData.orgId)
    if (res.code !== 20000) return showMsg(res.message)
    let {
      count
    } = res.data
    this.setData({
      teamTotal: count
    })
  },
  // 去团队管理
  goTeam() {
    if (app.globalData.orgId == 1) return showMsg("请先选择单位！")
    wx.navigateTo({
      url: '/packageA/pages/personal-inside-page/team/team?teamTotal=' + this.data.teamTotal,
    })
  },

  // 去重置密码
  goResetPwd() {
    wx.navigateTo({
      url: '/packageA/pages/personal-inside-page/reset-pwd/reset-pwd',
    })
  },

  goMoney() {
    wx.navigateTo({
      url: '/packageA/pages/personal-inside-page/money/money',
    })
  },

  goSubions() {
    wx.navigateTo({
      url: '/pages/personal-inside-page/subions/subions',
    })
  },

  /**
   * @name: 点击绑定/解绑微信  
   * @msg:   做定时，防止多次快速操作
   * @return {*}
   */
  // bindWxClick() {
  //     clearTimeout(timer)
  //     let {
  //         isBindWx
  //     } = this.data
  //     if (!isBindWx) return Toast("您操作太快啦，请稍后试试")
  //     if (isBindWx) {
  //         this.binxWxhandle()
  //         this.setData({
  //             isBindWx: false
  //         })
  //     }
  //     let timer = setTimeout(() => {
  //         this.setData({
  //             isBindWx: true
  //         })
  //     }, 5000)
  // },
  /**
   * @name: 解绑/绑定微信操作
   * @msg:   根据openId判断
   * @return {*}
   */
  bindWxClick() {
    let openId = wx.getStorageSync('openId')
    if (openId) {
      // 解绑
      this.unBindWx()
    } else {
      // 绑定
      // showModel('温馨提示', '是否绑定微信？', async (e) => {
      //     if (e) {
      this.bindWx()
      // } else {
      //     console.log('绑定取消')
      // }
      // })
    }
  },
  /**
   * @name: 绑定微信
   * @msg: 
   * @return {*}
   */
  bindWx() {
    let that = this
    wx.showLoading({
      title: '绑定中...',
      mask: true
    })
    wx.getUserProfile({
      desc: '用于获取微信基本信息',
      success: async function (res) {
        let {
          nickName: wxNickName,
          avatarUrl: wxAvatar
        } = res.userInfo
        wx.login({
          async success(res) {
            if (res.code) {
              const res1 = await reqWxUserInfo({
                jsCode: res.code
              }) //获取信息jsCode
              if (res1.code !== 20000) {
                wx.hideLoading()
                showMsg(res1.message)
                return
              }
              let {
                row
              } = res1.data
              let params = {
                id: app.globalData.userId,
                openId: row.openid,
                unionid: row.unionid,
                wxNickName,
                wxAvatar
              }
              const res2 = await reqBindWx(params) //绑定微信
              if (res2.code !== 20000) {
                wx.hideLoading()
                Toast(res2.message)
                return
              }
              app.globalData.wxNickName = wxNickName
              wx.setStorageSync('wxNickName', wxNickName)
              app.globalData.wxAvatar = wxAvatar
              wx.setStorageSync('wxAvatar', wxAvatar)
              that.setData({
                wxNickName,
                wxAvatar
              })
              app.globalData.openId = row.openid
              wx.setStorageSync('openId', row.openid) //微信openId
              that.setData({
                openId: row.openid
              })
              wx.hideLoading()
              wx.showToast({
                title: '绑定成功',
              })
            } else {
              console.log('绑定失败！' + res.errMsg)
              wx.hideLoading()
            }
          }
        })
      },
      fail: function (err) {
        wx.hideLoading()
        // 需要弹出隐私协议
        this.setData({
          innerShow: true
        })
        console.log(err, '获取用户基本信息');
      }
    })
  },
  /**
   * @name: 解绑微信
   * @msg: 
   * @return {*}
   */
  unBindWx() {
    let that = this
    wx.login({
      async success(res) {
        if (res.code) {
          showModel('温馨提示', '是否解绑？', async (e) => {
            if (e) {
              let params = {
                jsCode: res.code,
                id: app.globalData.userId
              }
              const res1 = await reqUnBindWx(params)
              if (res1.code !== 20000) return Toast(res1.message)
              app.globalData.openId = ''
              wx.removeStorageSync('openId')
              app.globalData.wxNickName = ''
              wx.removeStorageSync('wxNickName')
              app.globalData.wxAvatar = ''
              wx.removeStorageSync('wxAvatar')
              that.setData({
                wxNickName: '',
                wxAvatar: '',
                openId: ''
              })
              wx.showToast({
                title: '解绑成功',
              })
            }
          })
        } else {
          console.log('解绑失败！' + res.errMsg)
        }
      }
    })
  },

  // 绑定手机点击（虚）
  bindMobileClick() {},
  /**
   * @name: 绑定手机（真）
   * @msg:   1、先获取本机手机号   2、绑定手机号  
   * @params:  1、userId  2、mobile
   * @return {*}
   */
  // bindMobile(e) {
  // let that = this
  // wx.login({
  //     async success(res) {
  //         const res1 = await reqWxUserInfo({
  //             jsCode: res.code
  //         }) //获取信息
  //         if (res1.code !== 20000) return showMsg(res1.message)
  //         let {
  //             row
  //         } = res1.data
  //         // 解密
  //         let appId = 'wxda69189aa728178c'
  //         let encryptedData = e.detail.encryptedData
  //         let iv = e.detail.iv
  //         let pc = new WXBizDataCrypt(appId, row.session_key)
  //         let data = pc.decryptData(encryptedData, iv)
  //         if (!data) return showMsg("获取手机号码失败，请重试")
  //         let mobile = data.phoneNumber
  //         if (mobile == app.globalData.mobile) return Toast("手机号码重复")

  //         const res2 = await reqBindMobile({
  //             id: app.globalData.userId,
  //             mobile
  //         })
  //         if (res2.code !== 20000) return showMsg(res2.message)
  //         that.setData({
  //             mobile
  //         })
  //         app.globalData.mobile = mobile
  //         wx.setStorageSync('mobile', mobile)
  //         wx.showToast({
  //             title: '更换成功',
  //         })

  //     },
  // })
  // },

  bindMobile(e) {
    let that = this
    wx.login({
      async success() {
        const res = await reqGetPhoneNum({
          code: e.detail.code
        })
        if (res.code !== 20000) return
        let {
          phoneNumber
        } = res.data.row.phone_info
        let mobile = phoneNumber
        if (mobile == app.globalData.mobile) return showMsg("手机号码重复")

        const res2 = await reqBindMobile({
          id: app.globalData.userId,
          mobile
        })
        if (res2.code !== 20000) return showMsg(res2.message)
        that.setData({
          mobile
        })
        app.globalData.mobile = mobile
        wx.setStorageSync('mobile', mobile)
        wx.showToast({
          title: '更换成功',
        })
      },
      fail(err) {
        console.log(err);
      }
    })
  },

  // 更改手机号
  onChangePhone() {
    wx.navigateTo({
      url: '/pages/bindPhone/bindPhone',
    })
  },

  // 去订阅信息
  gosubscribe() {
    return showMsg("功能暂未开启，敬请期待！")
    wx.navigateTo({
      url: '/packageC/pages/personal-inside-page/subscribe/subscribe',
    })

  },

  // 去帮助
  goHelp() {
    wx.navigateTo({
      url: '/packageA/pages/personal-inside-page/help/help',
    })
  },

  // 去公众号
  goOfficeAccount() {
    wx.navigateTo({
      url: '/packageA/pages/personal-inside-page/office-account/office-account',
    })
  },

  // 注销账号
  async cancelAccount() {
    this.setData({
      showCancelAccount: true
    })
  },

  // 确定/取消
  handleAction(res) {
    console.log(res);
    const {
      msg,
      show
    } = res.detail
    if (msg === 'confirm') {
      // 注销
      this.clearStorage()
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/login/login',
        })
      }, 1000)
    }
    this.setData({
      showCancelAccount: show,
    })
  }

})